import Vue from 'vue';
import VueRouter from 'vue-router';
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

Vue.use(VueRouter);

const modulesFiles = require.context('./modules', true, /\.js$/);
var routeMap = [];
modulesFiles.keys().forEach((key) => {
  routeMap = routeMap.concat(modulesFiles(key).default);
});

const routes = [
  {
    path: '/login',
    name: 'login',
    meta: { title: '登录界面', isAuth: true },
    component: () => import(/* webpackChunkName: "did" */ '@/views/userIdentity/login.vue'),
  },
  {
    path: '/',
    name: 'welcome',
    meta: { title: '主界面', },
    component: () => import(/* webpackChunkName: "did" */ '@/views/login/welcome.vue'),
  },
  //读取所有路由信息
  ...routeMap,
];

const loginPath = '/login';

const router = new VueRouter({
  routes,
});

//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  //如果路由需要跳转
  if (to.meta.isAuth) {
    if (to.path === loginPath) {
      next();
      //判断 如果school本地存储是的时候，可以进去
    } else if (localStorage.getItem('loginState') == 1) {
      next()  //放行
    } else {
      next(loginPath)  //回到登录页面
      alert('抱歉，您无权限查看！')
    }
  } else {
    // 否则，放行
    next()
  }
})

export default router;

